<?php
class Poll_model extends CI_Model {

    function __construct() {
        parent::__construct();
        $this->load->database();
    }

    /**
     * When polls, create a new row to the database
     * @param $pid
     * @param $ip
     * @return bool
     */
    function insert($pid, $ip, $id) {
        $this->pid = $pid;
        $this->ip = $ip;
        $this->category = $id;
        // Check whether it has been existed
        $query = $this->db->get_where('pr_rates', array('ip' => $ip, 'category' => $id));
        $query = $query->row_array();

        if (!empty($query)) {
            return TRUE;
        } else {
            $this->db->insert('pr_rates', $this);
            return FALSE;
        }
    }

    /**
     * Count the poll
     * @return mixed
     */
    function count() {
        $pid = $this->input->get('pid');
        $query = $this->db->get_where('pr_rates', array('pid' => $pid));
        return $query->num_rows();      // return the rows and then show the number of rates
    }

    /**
     * rank by rates
     * @return mixed
     */
    function rank() {
        $query = $this->db->query("SELECT pr_rates.pid,count(pr_rates.ip),pr_works.title,pr_works.realname,pr_college.name, pr_category.category, pr_category.deadline FROM pr_works RIGHT JOIN pr_rates ON pr_rates.pid=pr_works.pid LEFT JOIN pr_college ON pr_works.college=pr_college.id LEFT JOIN pr_category ON pr_works.category=pr_category.id GROUP BY pid ORDER BY deadline DESC, count(pr_rates.ip) DESC");
        return $query->result_array();

    }
}